package com.inventory.controller;

import com.inventory.entity.Inventory;
import com.inventory.service.InventoryService;
import com.inventory.utils.ResponseResult;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api/inventory")
public class InventoryController {

    private static final Logger log = LoggerFactory.getLogger(InventoryController.class);

    @Autowired
    private InventoryService inventoryService;

    @Value("${server.port}")
    private String serverPort;

    /**
     * 获取库存列表（带熔断降级）
     */
    @GetMapping("/list.do")
    @CircuitBreaker(
            name = "inventoryService",
            fallbackMethod = "listFallback"
    )
    public ResponseResult getInventoryInfoList() {
        log.info("获取库存列表 - 端口: {}", serverPort);
        try {
            List<Inventory> list = inventoryService.doGetInventoryInfoList();
            return ResponseResult.build(list != null, null, list);
        } catch (Exception e) {
            log.error("获取库存列表异常", e);
            throw e;
        }
    }

    private ResponseResult listFallback(Throwable ex) {
        log.warn("库存列表熔断触发！端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(
                false,
                "服务繁忙，请稍后再试（端口：" + serverPort + "）",
                null
        );
    }
    /**
     * 添加库存信息
     */
    @PostMapping("/add.do")
    @CircuitBreaker(
            name = "inventoryService",
            fallbackMethod = "addFallback"
    )
    public ResponseResult addInventory(@RequestBody Inventory inventory) {
        log.info("添加库存信息 - 端口: {}", serverPort);
        try {
            boolean result = inventoryService.doAddInventoryInfo(inventory);
            return ResponseResult.build(result,
                    result ? "添加成功" : "添加失败",
                    null
            );
        } catch (Exception e) {
            log.error("添加库存异常", e);
            throw e;
        }
    }

    /**
     * 添加库存熔断降级方法
     */
    private ResponseResult addFallback(Inventory inventory, Throwable ex) {
        log.warn("添加库存熔断触发！端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(
                false,
                "服务繁忙，请稍后再试（端口：" + serverPort + "）",
                null
        );
    }

    /**
     * 修改库存信息
     */
    @PostMapping("/modify.do")
    @CircuitBreaker(
            name = "inventoryService",
            fallbackMethod = "modifyFallback"
    )
    public ResponseResult modifyInventoryInfo(@RequestBody Inventory inventory) {
        log.info("修改库存信息 - 端口: {}", serverPort);
        try {
            boolean result = inventoryService.doModifyInventoryInfo(inventory);
            return ResponseResult.build(result,
                    result ? "修改成功" : "修改失败，库存可能不存在",
                    null
            );
        } catch (Exception e) {
            log.error("修改库存异常", e);
            throw e;
        }
    }

    /**
     * 修改库存熔断降级方法
     */
    private ResponseResult modifyFallback(Inventory inventory, Throwable ex) {
        log.warn("修改库存熔断触发！端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(
                false,
                "服务繁忙，请稍后再试（端口：" + serverPort + "）",
                null
        );
    }

    /**
     * 删除库存信息
     */
    @PostMapping("/delete.do")
    @CircuitBreaker(
            name = "inventoryService",
            fallbackMethod = "deleteFallback"
    )
    public ResponseResult deleteInventory(@RequestParam Integer iid) {
        log.info("删除库存信息 - 端口: {}", serverPort);
        try {
            boolean result = inventoryService.doDeleteInventoryInfo(iid);
            return ResponseResult.build(result,
                    result ? "删除成功" : "删除失败，库存可能不存在",
                    null
            );
        } catch (Exception e) {
            log.error("删除库存异常", e);
            throw e;
        }
    }

    /**
     * 删除库存熔断降级方法
     */
    private ResponseResult deleteFallback(Integer iid, Throwable ex) {
        log.warn("删除库存熔断触发！端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(
                false,
                "服务繁忙，请稍后再试（端口：" + serverPort + "）",
                null
        );
    }
}